package top.lunarye.api.action;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import top.lunarye.api.domain.MessageParam;
import top.lunarye.api.domain.SendTaskModel;
import top.lunarye.common.enums.RespStatusEnum;
import top.lunarye.common.vo.BasicResultVO;
import top.lunarye.support.pipeline.BusinessProcess;
import top.lunarye.support.pipeline.ProcessContext;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 前置参数检查
 * @author lunar
 * @since 2022-07-11
 */
@Service
public class PreParamCheckAction implements BusinessProcess<SendTaskModel> {

    /**
     * 最大的接受消息的人数
     */
    private static final Integer BATCH_RECEIVER_SIZE = 1024;

    @Override
    public void process(ProcessContext<SendTaskModel> context) {
        SendTaskModel sendTaskModel = context.getProcessModel();

        Long messageTemplateId = sendTaskModel.getMessageTemplateId();
        List<MessageParam> messageParamList = sendTaskModel.getMessageParamList();

        // 没有传入 消息模板ID 或者 messageParam
        if (messageTemplateId == null || CollUtil.isEmpty(messageParamList)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS));
            return;
        }

        // 过滤接收者为空的消息
        List<MessageParam> resultMessageParamList = messageParamList.stream()
                .filter(messageParam -> !StrUtil.isBlank(messageParam.getReceiver())).toList();
        if (CollUtil.isEmpty(resultMessageParamList)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS));
            return;
        }
        sendTaskModel.setMessageParamList(resultMessageParamList);

        // 过滤接收者大于最大限制的消息
        if (messageParamList.stream()
                .anyMatch(messageParam -> messageParam.getReceiver()
                        .split(StrUtil.COMMA).length > BATCH_RECEIVER_SIZE)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.TOO_MANY_RECEIVER));
        }

    }
}
